3 * Base code for file repositories.
10 * Base class for file repositories
17 const DELETE_SOURCE
= 1;
19 const OVERWRITE_SAME
= 4;
20 const SKIP_LOCKING
= 8;
22 /** @var FileBackendBase */
24 /** @var Array Map of zones to config */
25 protected $zones = array();
27 var $thumbScriptUrl, $transformVia404;
28 var $descBaseUrl, $scriptDirUrl, $scriptExtension, $articleUrl;
29 var $fetchDescription, $initialCapital;
30 var $pathDisclosureProtection = 'simple'; // 'paranoid'
31 var $descriptionCacheExpiry, $url, $thumbUrl;
32 var $hashLevels, $deletedHashLevels;
35 * Factory functions for creating new files
36 * Override these in the base class
38 var $fileFactory = array( 'UnregisteredLocalFile', 'newFromTitle' );
39 var $oldFileFactory = false;
40 var $fileFactoryKey = false, $oldFileFactoryKey = false;
42 function __construct( $info ) {
44 $this->name
= $info['name'];
45 if ( $info['backend'] instanceof FileBackendBase
) {
46 $this->backend
= $info['backend']; // useful for testing
48 $this->backend
= FileBackendGroup
::singleton()->get( $info['backend'] );
51 // Optional settings that can have no value
52 $optionalSettings = array(
53 'descBaseUrl', 'scriptDirUrl', 'articleUrl', 'fetchDescription',
54 'thumbScriptUrl', 'pathDisclosureProtection', 'descriptionCacheExpiry',
57 foreach ( $optionalSettings as $var ) {
58 if ( isset( $info[$var] ) ) {
59 $this->$var = $info[$var];
63 // Optional settings that have a default
64 $this->initialCapital
= isset( $info['initialCapital'] )
65 ?
$info['initialCapital']
66 : MWNamespace
::isCapitalized( NS_FILE
);
67 $this->url
= isset( $info['url'] )
69 : false; // a subclass may set the URL (e.g. ForeignAPIRepo)
70 if ( isset( $info['thumbUrl'] ) ) {
71 $this->thumbUrl
= $info['thumbUrl'];
73 $this->thumbUrl
= $this->url ?
"{$this->url}/thumb" : false;
75 $this->hashLevels
= isset( $info['hashLevels'] )
78 $this->deletedHashLevels
= isset( $info['deletedHashLevels'] )
79 ?
$info['deletedHashLevels']
81 $this->transformVia404
= !empty( $info['transformVia404'] );
82 $this->zones
= isset( $info['zones'] )
85 // Give defaults for the basic zones...
86 foreach ( array( 'public', 'thumb', 'temp', 'deleted' ) as $zone ) {
87 if ( !isset( $this->zones
[$zone] ) ) {
88 if ( $zone === 'deleted' ) {
89 $this->zones
[$zone] = array(
90 'container' => null, // user must set this up
91 'directory' => '' // container root
94 $this->zones
[$zone] = array(
95 'container' => "media-$zone",
96 'directory' => '' // container root
104 * Get the file backend instance
106 * @return FileBackendBase
108 public function getBackend() {
109 return $this->backend
;
113 * Prepare all the zones for basic usage.
114 * See initDeletedDir() for additional setup needed for the 'deleted' zone.
116 * @param $doZones Array Only do a particular zones
119 protected function initZones( $doZones = array() ) {
120 $status = $this->newGood();
121 $doZones = (array)$doZones; // string => array
122 foreach ( $this->zones
as $zone => $info ) {
123 if ( $doZones && !in_array( $zone, $doZones ) ) {
126 $root = $this->getZonePath( $zone );
127 if ( $root !== null ) {
128 $params = array( 'dir' => $this->getZonePath( $zone ) );
129 $status->merge( $this->backend
->prepare( $params ) );
136 * Take all available measures to prevent web accessibility of new deleted
137 * directories, in case the user has not configured offline storage
141 protected function initDeletedDir( $dir ) {
142 // Add a .htaccess file to the root of the deleted zone
143 $root = $this->getZonePath( 'deleted' );
144 $this->backend
->secure( array( 'dir' => $root, 'noAccess' => true ) );
145 // Seed new directories with a blank index.html, to prevent crawling
146 $this->backend
->secure( array( 'dir' => $dir, 'noListing' => true ) );
150 * Determine if a string is an mwrepo:// URL
155 public static function isVirtualUrl( $url ) {
156 return substr( $url, 0, 9 ) == 'mwrepo://';
160 * Get a URL referring to this repository, with the private mwrepo protocol.
161 * The suffix, if supplied, is considered to be unencoded, and will be
162 * URL-encoded before being returned.
164 * @param $suffix string
167 public function getVirtualUrl( $suffix = false ) {
168 $path = 'mwrepo://' . $this->name
;
169 if ( $suffix !== false ) {
170 $path .= '/' . rawurlencode( $suffix );
176 * Get the URL corresponding to one of the four basic zones
178 * @param $zone String: one of: public, deleted, temp, thumb
179 * @return String or false
181 public function getZoneUrl( $zone ) {
186 return "{$this->url}/temp";
188 return false; // no public URL
190 return $this->thumbUrl
;
197 * Get the backend storage path corresponding to a virtual URL
202 function resolveVirtualUrl( $url ) {
203 if ( substr( $url, 0, 9 ) != 'mwrepo://' ) {
204 throw new MWException( __METHOD__
.': unknown protocol' );
206 $bits = explode( '/', substr( $url, 9 ), 3 );
207 if ( count( $bits ) != 3 ) {
208 throw new MWException( __METHOD__
.": invalid mwrepo URL: $url" );
210 list( $repo, $zone, $rel ) = $bits;
211 if ( $repo !== $this->name
) {
212 throw new MWException( __METHOD__
.": fetching from a foreign repo is not supported" );
214 $base = $this->getZonePath( $zone );
216 throw new MWException( __METHOD__
.": invalid zone: $zone" );
218 return $base . '/' . rawurldecode( $rel );
222 * The the storage container and base path of a zone
224 * @param $zone string
225 * @return Array (container, base path) or (null, null)
227 protected function getZoneLocation( $zone ) {
228 if ( !isset( $this->zones
[$zone] ) ) {
229 return array( null, null ); // bogus
231 return array( $this->zones
[$zone]['container'], $this->zones
[$zone]['directory'] );
235 * Get the storage path corresponding to one of the zones
237 * @param $zone string
238 * @return string|null
240 public function getZonePath( $zone ) {
241 list( $container, $base ) = $this->getZoneLocation( $zone );
242 if ( $container === null ||
$base === null ) {
245 $backendName = $this->backend
->getName();
246 if ( $base != '' ) { // may not be set
249 return "mwstore://$backendName/{$container}{$base}";
253 * Create a new File object from the local repository
255 * @param $title Mixed: Title object or string
256 * @param $time Mixed: Time at which the image was uploaded.
257 * If this is specified, the returned object will be an
258 * instance of the repository's old file class instead of a
259 * current file. Repositories not supporting version control
260 * should return false if this parameter is set.
261 * @return File|null A File, or null if passed an invalid Title
263 public function newFile( $title, $time = false ) {
264 $title = File
::normalizeTitle( $title );
269 if ( $this->oldFileFactory
) {
270 return call_user_func( $this->oldFileFactory
, $title, $this, $time );
275 return call_user_func( $this->fileFactory
, $title, $this );
280 * Find an instance of the named file created at the specified time
281 * Returns false if the file does not exist. Repositories not supporting
282 * version control should return false if the time is specified.
284 * @param $title Mixed: Title object or string
285 * @param $options array Associative array of options:
286 * time: requested time for an archived image, or false for the
287 * current version. An image object will be returned which was
288 * created at the specified time.
290 * ignoreRedirect: If true, do not follow file redirects
292 * private: If true, return restricted (deleted) files if the current
293 * user is allowed to view them. Otherwise, such files will not
297 public function findFile( $title, $options = array() ) {
298 $title = File
::normalizeTitle( $title );
302 $time = isset( $options['time'] ) ?
$options['time'] : false;
303 # First try the current version of the file to see if it precedes the timestamp
304 $img = $this->newFile( $title );
308 if ( $img->exists() && ( !$time ||
$img->getTimestamp() == $time ) ) {
311 # Now try an old version of the file
312 if ( $time !== false ) {
313 $img = $this->newFile( $title, $time );
314 if ( $img && $img->exists() ) {
315 if ( !$img->isDeleted( File
::DELETED_FILE
) ) {
316 return $img; // always OK
317 } elseif ( !empty( $options['private'] ) && $img->userCan( File
::DELETED_FILE
) ) {
324 if ( !empty( $options['ignoreRedirect'] ) ) {
327 $redir = $this->checkRedirect( $title );
328 if ( $redir && $title->getNamespace() == NS_FILE
) {
329 $img = $this->newFile( $redir );
333 if ( $img->exists() ) {
334 $img->redirectedFrom( $title->getDBkey() );
342 * Find many files at once.
344 * @param $items An array of titles, or an array of findFile() options with
345 * the "title" option giving the title. Example:
347 * $findItem = array( 'title' => $title, 'private' => true );
348 * $findBatch = array( $findItem );
349 * $repo->findFiles( $findBatch );
352 public function findFiles( $items ) {
354 foreach ( $items as $item ) {
355 if ( is_array( $item ) ) {
356 $title = $item['title'];
358 unset( $options['title'] );
363 $file = $this->findFile( $title, $options );
365 $result[$file->getTitle()->getDBkey()] = $file;
372 * Find an instance of the file with this key, created at the specified time
373 * Returns false if the file does not exist. Repositories not supporting
374 * version control should return false if the time is specified.
376 * @param $sha1 String base 36 SHA-1 hash
377 * @param $options Option array, same as findFile().
380 public function findFileFromKey( $sha1, $options = array() ) {
381 $time = isset( $options['time'] ) ?
$options['time'] : false;
383 # First try to find a matching current version of a file...
384 if ( $this->fileFactoryKey
) {
385 $img = call_user_func( $this->fileFactoryKey
, $sha1, $this, $time );
387 return false; // find-by-sha1 not supported
389 if ( $img && $img->exists() ) {
392 # Now try to find a matching old version of a file...
393 if ( $time !== false && $this->oldFileFactoryKey
) { // find-by-sha1 supported?
394 $img = call_user_func( $this->oldFileFactoryKey
, $sha1, $this, $time );
395 if ( $img && $img->exists() ) {
396 if ( !$img->isDeleted( File
::DELETED_FILE
) ) {
397 return $img; // always OK
398 } elseif ( !empty( $options['private'] ) && $img->userCan( File
::DELETED_FILE
) ) {
407 * Get an array or iterator of file objects for files that have a given
408 * SHA-1 content hash.
412 public function findBySha1( $hash ) {
417 * Get the public root URL of the repository
419 * @return string|false
421 public function getRootUrl() {
426 * Returns true if the repository uses a multi-level directory structure
430 public function isHashed() {
431 return (bool)$this->hashLevels
;
435 * Get the URL of thumb.php
439 public function getThumbScriptUrl() {
440 return $this->thumbScriptUrl
;
444 * Returns true if the repository can transform files via a 404 handler
448 public function canTransformVia404() {
449 return $this->transformVia404
;
453 * Get the name of an image from its title object
455 * @param $title Title
457 public function getNameFromTitle( Title
$title ) {
459 if ( $this->initialCapital
!= MWNamespace
::isCapitalized( NS_FILE
) ) {
460 $name = $title->getUserCaseDBKey();
461 if ( $this->initialCapital
) {
462 $name = $wgContLang->ucfirst( $name );
465 $name = $title->getDBkey();
471 * Get the public zone root storage directory of the repository
475 public function getRootDirectory() {
476 return $this->getZonePath( 'public' );
480 * Get a relative path including trailing slash, e.g. f/fa/
481 * If the repo is not hashed, returns an empty string
483 * @param $name string
486 public function getHashPath( $name ) {
487 return self
::getHashPathForLevel( $name, $this->hashLevels
);
495 static function getHashPathForLevel( $name, $levels ) {
496 if ( $levels == 0 ) {
499 $hash = md5( $name );
501 for ( $i = 1; $i <= $levels; $i++
) {
502 $path .= substr( $hash, 0, $i ) . '/';
509 * Get the number of hash directory levels
513 public function getHashLevels() {
514 return $this->hashLevels
;
518 * Get the name of this repository, as specified by $info['name]' to the constructor
522 public function getName() {
527 * Make an url to this repo
529 * @param $query mixed Query string to append
530 * @param $entry string Entry point; defaults to index
531 * @return string|false
533 public function makeUrl( $query = '', $entry = 'index' ) {
534 if ( isset( $this->scriptDirUrl
) ) {
535 $ext = isset( $this->scriptExtension
) ?
$this->scriptExtension
: '.php';
536 return wfAppendQuery( "{$this->scriptDirUrl}/{$entry}{$ext}", $query );
542 * Get the URL of an image description page. May return false if it is
543 * unknown or not applicable. In general this should only be called by the
544 * File class, since it may return invalid results for certain kinds of
545 * repositories. Use File::getDescriptionUrl() in user code.
547 * In particular, it uses the article paths as specified to the repository
548 * constructor, whereas local repositories use the local Title functions.
550 * @param $name string
553 public function getDescriptionUrl( $name ) {
554 $encName = wfUrlencode( $name );
555 if ( !is_null( $this->descBaseUrl
) ) {
556 # "http://example.com/wiki/Image:"
557 return $this->descBaseUrl
. $encName;
559 if ( !is_null( $this->articleUrl
) ) {
560 # "http://example.com/wiki/$1"
562 # We use "Image:" as the canonical namespace for
563 # compatibility across all MediaWiki versions.
564 return str_replace( '$1',
565 "Image:$encName", $this->articleUrl
);
567 if ( !is_null( $this->scriptDirUrl
) ) {
568 # "http://example.com/w"
570 # We use "Image:" as the canonical namespace for
571 # compatibility across all MediaWiki versions,
572 # and just sort of hope index.php is right. ;)
573 return $this->makeUrl( "title=Image:$encName" );
579 * Get the URL of the content-only fragment of the description page. For
580 * MediaWiki this means action=render. This should only be called by the
581 * repository's file class, since it may return invalid results. User code
582 * should use File::getDescriptionText().
584 * @param $name String: name of image to fetch
585 * @param $lang String: language to fetch it in, if any.
588 public function getDescriptionRenderUrl( $name, $lang = null ) {
589 $query = 'action=render';
590 if ( !is_null( $lang ) ) {
591 $query .= '&uselang=' . $lang;
593 if ( isset( $this->scriptDirUrl
) ) {
594 return $this->makeUrl(
596 wfUrlencode( 'Image:' . $name ) .
599 $descUrl = $this->getDescriptionUrl( $name );
601 return wfAppendQuery( $descUrl, $query );
609 * Get the URL of the stylesheet to apply to description pages
611 * @return string|false
613 public function getDescriptionStylesheetUrl() {
614 if ( isset( $this->scriptDirUrl
) ) {
615 return $this->makeUrl( 'title=MediaWiki:Filepage.css&' .
616 wfArrayToCGI( Skin
::getDynamicStylesheetQuery() ) );
622 * Store a file to a given destination.
624 * @param $srcPath String: source FS path, storage path, or virtual URL
625 * @param $dstZone String: destination zone
626 * @param $dstRel String: destination relative path
627 * @param $flags Integer: bitwise combination of the following flags:
628 * self::DELETE_SOURCE Delete the source file after upload
629 * self::OVERWRITE Overwrite an existing destination file instead of failing
630 * self::OVERWRITE_SAME Overwrite the file if the destination exists and has the
631 * same contents as the source
632 * self::SKIP_LOCKING Skip any file locking when doing the store
633 * @return FileRepoStatus
635 public function store( $srcPath, $dstZone, $dstRel, $flags = 0 ) {
636 $status = $this->storeBatch( array( array( $srcPath, $dstZone, $dstRel ) ), $flags );
637 if ( $status->successCount
== 0 ) {
644 * Store a batch of files
646 * @param $triplets Array: (src, dest zone, dest rel) triplets as per store()
647 * @param $flags Integer: bitwise combination of the following flags:
648 * self::DELETE_SOURCE Delete the source file after upload
649 * self::OVERWRITE Overwrite an existing destination file instead of failing
650 * self::OVERWRITE_SAME Overwrite the file if the destination exists and has the
651 * same contents as the source
652 * self::SKIP_LOCKING Skip any file locking when doing the store
653 * @return FileRepoStatus
655 public function storeBatch( $triplets, $flags = 0 ) {
656 $backend = $this->backend
; // convenience
658 $status = $this->newGood();
660 $operations = array();
661 $sourceFSFilesToDelete = array(); // cleanup for disk source files
662 // Validate each triplet and get the store operation...
663 foreach ( $triplets as $i => $triplet ) {
664 list( $srcPath, $dstZone, $dstRel ) = $triplet;
666 // Resolve destination path
667 $root = $this->getZonePath( $dstZone );
669 throw new MWException( "Invalid zone: $dstZone" );
671 if ( !$this->validateFilename( $dstRel ) ) {
672 throw new MWException( 'Validation error in $dstRel' );
674 $dstPath = "$root/$dstRel";
675 $dstDir = dirname( $dstPath );
677 // Create destination directories for this triplet
678 if ( !$backend->prepare( array( 'dir' => $dstDir ) )->isOK() ) {
679 return $this->newFatal( 'directorycreateerror', $dstDir );
682 if ( $dstZone == 'deleted' ) {
683 $this->initDeletedDir( $dstDir );
686 // Resolve source to a storage path if virtual
687 if ( self
::isVirtualUrl( $srcPath ) ) {
688 $srcPath = $this->resolveVirtualUrl( $srcPath );
691 // Get the appropriate file operation
692 if ( FileBackend
::isStoragePath( $srcPath ) ) {
693 $opName = ( $flags & self
::DELETE_SOURCE
) ?
'move' : 'copy';
696 if ( $flags & self
::DELETE_SOURCE
) {
697 $sourceFSFilesToDelete[] = $srcPath;
700 $operations[] = array(
704 'overwriteDest' => $flags & self
::OVERWRITE
,
705 'overwriteSame' => $flags & self
::OVERWRITE_SAME
,
709 // Execute the store operation for each triplet
710 $opts = array( 'ignoreErrors' => true );
711 if ( $flags & self
::SKIP_LOCKING
) {
712 $opts['nonLocking'] = true;
714 $status->merge( $backend->doOperations( $operations, $opts ) );
715 // Cleanup for disk source files...
716 foreach ( $sourceFSFilesToDelete as $file ) {
717 wfSuppressWarnings();
718 unlink( $file ); // FS cleanup
726 * Deletes a batch of files.
727 * Each file can be a (zone, rel) pair, virtual url, storage path, or FS path.
728 * It will try to delete each file, but ignores any errors that may occur.
730 * @param $pairs array List of files to delete
733 public function cleanupBatch( $files ) {
734 $operations = array();
735 $sourceFSFilesToDelete = array(); // cleanup for disk source files
736 foreach ( $files as $file ) {
737 if ( is_array( $file ) ) {
738 // This is a pair, extract it
739 list( $zone, $rel ) = $file;
740 $root = $this->getZonePath( $zone );
741 $path = "$root/$rel";
743 if ( self
::isVirtualUrl( $file ) ) {
744 // This is a virtual url, resolve it
745 $path = $this->resolveVirtualUrl( $file );
747 // This is a full file name
751 // Get a file operation if needed
752 if ( FileBackend
::isStoragePath( $path ) ) {
753 $operations[] = array(
758 $sourceFSFilesToDelete[] = $path;
761 // Actually delete files from storage...
762 $opts = array( 'ignoreErrors' => true );
763 $this->backend
->doOperations( $operations, $opts );
764 // Cleanup for disk source files...
765 foreach ( $sourceFSFilesToDelete as $file ) {
766 wfSuppressWarnings();
767 unlink( $path ); // FS cleanup
773 * Pick a random name in the temp zone and store a file to it.
774 * Returns a FileRepoStatus object with the URL in the value.
776 * @param $originalName String: the base name of the file as specified
777 * by the user. The file extension will be maintained.
778 * @param $srcPath String: the current location of the file.
779 * @return FileRepoStatus object with the URL in the value.
781 public function storeTemp( $originalName, $srcPath ) {
782 $date = gmdate( "YmdHis" );
783 $hashPath = $this->getHashPath( $originalName );
784 $dstRel = "{$hashPath}{$date}!{$originalName}";
785 $dstUrlRel = $hashPath . $date . '!' . rawurlencode( $originalName );
787 $result = $this->store( $srcPath, 'temp', $dstRel, self
::SKIP_LOCKING
);
788 $result->value
= $this->getVirtualUrl( 'temp' ) . '/' . $dstUrlRel;
793 * Concatenate a list of files into a target file location.
795 * @param $srcPaths Array Ordered list of source virtual URLs/storage paths
796 * @param $dstPath String Target virtual URL/storage path
797 * @param $flags Integer: bitwise combination of the following flags:
798 * self::DELETE_SOURCE Delete the source files
799 * @return FileRepoStatus
801 function concatenate( $srcPaths, $dstPath, $flags = 0 ) {
802 $status = $this->newGood();
803 // Resolve target to a storage path if virtual
804 $dest = $this->resolveToStoragePath( $dstPath );
807 $deleteOperations = array(); // post-concatenate ops
808 foreach ( $srcPaths as $srcPath ) {
809 // Resolve source to a storage path if virtual
810 $source = $this->resolveToStoragePath( $srcPath );
811 $sources[] = $source; // chunk to merge
812 if ( $flags & self
::DELETE_SOURCE
) {
813 $deleteOperations[] = array( 'op' => 'delete', 'src' => $source );
817 // Concatenate the chunks into one file
818 $op = array( 'op' => 'concatenate',
819 'srcs' => $sources, 'dst' => $dest, 'overwriteDest' => true );
820 $status->merge( $this->backend
->doOperation( $op ) );
821 if ( !$status->isOK() ) {
825 // Delete the sources if required
826 if ( $deleteOperations ) {
827 $opts = array( 'ignoreErrors' => true );
828 $status->merge( $this->backend
->doOperations( $deleteOperations, $opts ) );
831 // Make sure status is OK, despite any $deleteOperations fatals
832 $status->setResult( true );
838 * Remove a temporary file or mark it for garbage collection
840 * @param $virtualUrl String: the virtual URL returned by storeTemp
841 * @return Boolean: true on success, false on failure
843 public function freeTemp( $virtualUrl ) {
844 $temp = "mwrepo://{$this->name}/temp";
845 if ( substr( $virtualUrl, 0, strlen( $temp ) ) != $temp ) {
846 wfDebug( __METHOD__
.": Invalid temp virtual URL\n" );
849 $path = $this->resolveVirtualUrl( $virtualUrl );
850 $op = array( 'op' => 'delete', 'src' => $path );
851 $status = $this->backend
->doOperation( $op );
852 return $status->isOK();
856 * Copy or move a file either from a storage path, virtual URL,
857 * or FS path, into this repository at the specified destination location.
859 * Returns a FileRepoStatus object. On success, the value contains "new" or
860 * "archived", to indicate whether the file was new with that name.
862 * @param $srcPath String: the source FS path, storage path, or URL
863 * @param $dstRel String: the destination relative path
864 * @param $archiveRel String: the relative path where the existing file is to
865 * be archived, if there is one. Relative to the public zone root.
866 * @param $flags Integer: bitfield, may be FileRepo::DELETE_SOURCE to indicate
867 * that the source file should be deleted if possible
869 public function publish( $srcPath, $dstRel, $archiveRel, $flags = 0 ) {
870 $status = $this->publishBatch( array( array( $srcPath, $dstRel, $archiveRel ) ), $flags );
871 if ( $status->successCount
== 0 ) {
874 if ( isset( $status->value
[0] ) ) {
875 $status->value
= $status->value
[0];
877 $status->value
= false;
883 * Publish a batch of files
885 * @param $triplets Array: (source, dest, archive) triplets as per publish()
886 * @param $flags Integer: bitfield, may be FileRepo::DELETE_SOURCE to indicate
887 * that the source files should be deleted if possible
888 * @return FileRepoStatus
890 public function publishBatch( $triplets, $flags = 0 ) {
891 $backend = $this->backend
; // convenience
893 // Try creating directories
894 $status = $this->initZones( 'public' );
895 if ( !$status->isOK() ) {
899 $status = $this->newGood( array() );
901 $operations = array();
902 $sourceFSFilesToDelete = array(); // cleanup for disk source files
903 // Validate each triplet and get the store operation...
904 foreach ( $triplets as $i => $triplet ) {
905 list( $srcPath, $dstRel, $archiveRel ) = $triplet;
906 // Resolve source to a storage path if virtual
907 if ( substr( $srcPath, 0, 9 ) == 'mwrepo://' ) {
908 $srcPath = $this->resolveVirtualUrl( $srcPath );
910 if ( !$this->validateFilename( $dstRel ) ) {
911 throw new MWException( 'Validation error in $dstRel' );
913 if ( !$this->validateFilename( $archiveRel ) ) {
914 throw new MWException( 'Validation error in $archiveRel' );
917 $publicRoot = $this->getZonePath( 'public' );
918 $dstPath = "$publicRoot/$dstRel";
919 $archivePath = "$publicRoot/$archiveRel";
921 $dstDir = dirname( $dstPath );
922 $archiveDir = dirname( $archivePath );
923 // Abort immediately on directory creation errors since they're likely to be repetitive
924 if ( !$backend->prepare( array( 'dir' => $dstDir ) )->isOK() ) {
925 return $this->newFatal( 'directorycreateerror', $dstDir );
927 if ( !$backend->prepare( array( 'dir' => $archiveDir ) )->isOK() ) {
928 return $this->newFatal( 'directorycreateerror', $archiveDir );
931 // Archive destination file if it exists
932 if ( $backend->fileExists( array( 'src' => $dstPath ) ) ) {
933 // Check if the archive file exists
934 // This is a sanity check to avoid data loss. In UNIX, the rename primitive
935 // unlinks the destination file if it exists. DB-based synchronisation in
936 // publishBatch's caller should prevent races. In Windows there's no
937 // problem because the rename primitive fails if the destination exists.
938 if ( $backend->fileExists( array( 'src' => $archivePath ) ) ) {
939 $operations[] = array( 'op' => 'null' );
942 $operations[] = array(
945 'dst' => $archivePath
948 $status->value
[$i] = 'archived';
950 $status->value
[$i] = 'new';
952 // Copy (or move) the source file to the destination
953 if ( FileBackend
::isStoragePath( $srcPath ) ) {
954 if ( $flags & self
::DELETE_SOURCE
) {
955 $operations[] = array(
961 $operations[] = array(
967 } else { // FS source path
968 $operations[] = array(
973 if ( $flags & self
::DELETE_SOURCE
) {
974 $sourceFSFilesToDelete[] = $srcPath;
979 // Execute the operations for each triplet
980 $opts = array( 'ignoreErrors' => true );
981 $status->merge( $backend->doOperations( $operations, $opts ) );
982 // Cleanup for disk source files...
983 foreach ( $sourceFSFilesToDelete as $file ) {
984 wfSuppressWarnings();
985 unlink( $file ); // FS cleanup
993 * Checks existence of a a file
995 * @param $file Virtual URL (or storage path) of file to check
996 * @param $flags Integer: bitwise combination of the following flags:
997 * self::FILES_ONLY Mark file as existing only if it is a file (not directory)
1000 public function fileExists( $file, $flags = 0 ) {
1001 $result = $this->fileExistsBatch( array( $file ), $flags );
1006 * Checks existence of an array of files.
1008 * @param $files Array: Virtual URLs (or storage paths) of files to check
1009 * @param $flags Integer: bitwise combination of the following flags:
1010 * self::FILES_ONLY Mark file as existing only if it is a file (not directory)
1011 * @return Either array of files and existence flags, or false
1013 public function fileExistsBatch( $files, $flags = 0 ) {
1015 foreach ( $files as $key => $file ) {
1016 if ( self
::isVirtualUrl( $file ) ) {
1017 $file = $this->resolveVirtualUrl( $file );
1019 if ( FileBackend
::isStoragePath( $file ) ) {
1020 $result[$key] = $this->backend
->fileExists( array( 'src' => $file ) );
1022 if ( $flags & self
::FILES_ONLY
) {
1023 $result[$key] = is_file( $file ); // FS only
1025 $result[$key] = file_exists( $file ); // FS only
1034 * Move a file to the deletion archive.
1035 * If no valid deletion archive exists, this may either delete the file
1036 * or throw an exception, depending on the preference of the repository
1038 * @param $srcRel Mixed: relative path for the file to be deleted
1039 * @param $archiveRel Mixed: relative path for the archive location.
1040 * Relative to a private archive directory.
1041 * @return FileRepoStatus object
1043 public function delete( $srcRel, $archiveRel ) {
1044 return $this->deleteBatch( array( array( $srcRel, $archiveRel ) ) );
1048 * Move a group of files to the deletion archive.
1050 * If no valid deletion archive is configured, this may either delete the
1051 * file or throw an exception, depending on the preference of the repository.
1053 * The overwrite policy is determined by the repository -- currently LocalRepo
1054 * assumes a naming scheme in the deleted zone based on content hash, as
1055 * opposed to the public zone which is assumed to be unique.
1057 * @param $sourceDestPairs Array of source/destination pairs. Each element
1058 * is a two-element array containing the source file path relative to the
1059 * public root in the first element, and the archive file path relative
1060 * to the deleted zone root in the second element.
1061 * @return FileRepoStatus
1063 public function deleteBatch( $sourceDestPairs ) {
1064 $backend = $this->backend
; // convenience
1066 if ( !isset( $this->zones
['deleted']['container'] ) ) {
1067 throw new MWException( __METHOD__
.': no valid deletion archive directory' );
1070 // Try creating directories
1071 $status = $this->initZones( array( 'public', 'deleted' ) );
1072 if ( !$status->isOK() ) {
1076 $status = $this->newGood();
1078 $operations = array();
1079 // Validate filenames and create archive directories
1080 foreach ( $sourceDestPairs as $pair ) {
1081 list( $srcRel, $archiveRel ) = $pair;
1082 if ( !$this->validateFilename( $srcRel ) ) {
1083 throw new MWException( __METHOD__
.':Validation error in $srcRel' );
1085 if ( !$this->validateFilename( $archiveRel ) ) {
1086 throw new MWException( __METHOD__
.':Validation error in $archiveRel' );
1089 $publicRoot = $this->getZonePath( 'public' );
1090 $srcPath = "{$publicRoot}/$srcRel";
1092 $deletedRoot = $this->getZonePath( 'deleted' );
1093 $archivePath = "{$deletedRoot}/{$archiveRel}";
1094 $archiveDir = dirname( $archivePath ); // does not touch FS
1096 // Create destination directories
1097 if ( !$backend->prepare( array( 'dir' => $archiveDir ) )->isOK() ) {
1098 return $this->newFatal( 'directorycreateerror', $archiveDir );
1100 $this->initDeletedDir( $archiveDir );
1102 if ( $backend->fileExists( array( 'src' => $archivePath ) ) ) {
1103 $operations[] = array(
1108 $operations[] = array(
1111 'dst' => $archivePath
1116 // Move the files by execute the operations for each pair.
1117 // We're now committed to returning an OK result, which will
1118 // lead to the files being moved in the DB also.
1119 $opts = array( 'ignoreErrors' => true );
1120 $status->merge( $backend->doOperations( $operations, $opts ) );
1126 * Get a relative path for a deletion archive key,
1127 * e.g. s/z/a/ for sza251lrxrc1jad41h5mgilp8nysje52.jpg
1131 public function getDeletedHashPath( $key ) {
1133 for ( $i = 0; $i < $this->deletedHashLevels
; $i++
) {
1134 $path .= $key[$i] . '/';
1140 * If a path is a virtual URL, resolve it to a storage path.
1141 * Otherwise, just return the path as it is.
1143 * @param $path string
1145 * @throws MWException
1147 protected function resolveToStoragePath( $path ) {
1148 if ( $this->isVirtualUrl( $path ) ) {
1149 return $this->resolveVirtualUrl( $path );
1155 * Get a local FS copy of a file with a given virtual URL/storage path.
1156 * Temporary files may be purged when the file object falls out of scope.
1158 * @param $virtualUrl string
1159 * @return TempFSFile|null Returns null on failure
1161 public function getLocalCopy( $virtualUrl ) {
1162 $path = $this->resolveToStoragePath( $virtualUrl );
1163 return $this->backend
->getLocalCopy( array( 'src' => $path ) );
1167 * Get a local FS file with a given virtual URL/storage path.
1168 * The file is either an original or a copy. It should not be changed.
1169 * Temporary files may be purged when the file object falls out of scope.
1171 * @param $virtualUrl string
1172 * @return FSFile|null Returns null on failure.
1174 public function getLocalReference( $virtualUrl ) {
1175 $path = $this->resolveToStoragePath( $virtualUrl );
1176 return $this->backend
->getLocalReference( array( 'src' => $path ) );
1180 * Get properties of a file with a given virtual URL/storage path.
1181 * Properties should ultimately be obtained via FSFile::getProps().
1183 * @param $virtualUrl string
1186 public function getFileProps( $virtualUrl ) {
1187 $path = $this->resolveToStoragePath( $virtualUrl );
1188 return $this->backend
->getFileProps( array( 'src' => $path ) );
1192 * Get the timestamp of a file with a given virtual URL/storage path
1194 * @param $virtualUrl string
1195 * @return string|false
1197 public function getFileTimestamp( $virtualUrl ) {
1198 $path = $this->resolveToStoragePath( $virtualUrl );
1199 return $this->backend
->getFileTimestamp( array( 'src' => $path ) );
1203 * Get the sha1 of a file with a given virtual URL/storage path
1205 * @param $virtualUrl string
1206 * @return string|false
1208 public function getFileSha1( $virtualUrl ) {
1209 $path = $this->resolveToStoragePath( $virtualUrl );
1210 $tmpFile = $this->backend
->getLocalReference( array( 'src' => $path ) );
1214 return $tmpFile->getSha1Base36();
1218 * Attempt to stream a file with the given virtual URL/storage path
1220 * @param $virtualUrl string
1221 * @param $headers Array Additional HTTP headers to send on success
1222 * @return bool Success
1224 public function streamFile( $virtualUrl, $headers = array() ) {
1225 $path = $this->resolveToStoragePath( $virtualUrl );
1226 $params = array( 'src' => $path, 'headers' => $headers );
1227 return $this->backend
->streamFile( $params )->isOK();
1231 * Call a callback function for every public file in the repository.
1232 * May use either the database or the filesystem.
1234 * @param $callback Array|string
1237 public function enumFiles( $callback ) {
1238 return $this->enumFilesInStorage( $callback );
1242 * Call a callback function for every public file in the repository.
1243 * May use either the database or the filesystem.
1245 * @param $callback Array|string
1248 protected function enumFilesInStorage( $callback ) {
1249 $publicRoot = $this->getZonePath( 'public' );
1250 $numDirs = 1 << ( $this->hashLevels
* 4 );
1251 // Use a priori assumptions about directory structure
1252 // to reduce the tree height of the scanning process.
1253 for ( $flatIndex = 0; $flatIndex < $numDirs; $flatIndex++
) {
1254 $hexString = sprintf( "%0{$this->hashLevels}x", $flatIndex );
1255 $path = $publicRoot;
1256 for ( $hexPos = 0; $hexPos < $this->hashLevels
; $hexPos++
) {
1257 $path .= '/' . substr( $hexString, 0, $hexPos +
1 );
1259 $iterator = $this->backend
->getFileList( array( 'dir' => $path ) );
1260 foreach ( $iterator as $name ) {
1261 // Each item returned is a public file
1262 call_user_func( $callback, "{$path}/{$name}" );
1268 * Determine if a relative path is valid, i.e. not blank or involving directory traveral
1270 * @param $filename string
1273 public function validateFilename( $filename ) {
1274 if ( strval( $filename ) == '' ) {
1277 if ( wfIsWindows() ) {
1278 $filename = strtr( $filename, '\\', '/' );
1281 * Use the same traversal protection as Title::secureAndSplit()
1283 if ( strpos( $filename, '.' ) !== false &&
1284 ( $filename === '.' ||
$filename === '..' ||
1285 strpos( $filename, './' ) === 0 ||
1286 strpos( $filename, '../' ) === 0 ||
1287 strpos( $filename, '/./' ) !== false ||
1288 strpos( $filename, '/../' ) !== false ) )
1297 * Get a callback function to use for cleaning error message parameters
1301 function getErrorCleanupFunction() {
1302 switch ( $this->pathDisclosureProtection
) {
1304 $callback = array( $this, 'passThrough' );
1307 $callback = array( $this, 'simpleClean' );
1309 default: // 'paranoid'
1310 $callback = array( $this, 'paranoidClean' );
1316 * Path disclosure protection function
1318 * @param $param string
1321 function paranoidClean( $param ) {
1326 * Path disclosure protection function
1328 * @param $param string
1331 function simpleClean( $param ) {
1333 if ( !isset( $this->simpleCleanPairs
) ) {
1334 $this->simpleCleanPairs
= array(
1335 $IP => '$IP', // sanity
1338 return strtr( $param, $this->simpleCleanPairs
);
1342 * Path disclosure protection function
1344 * @param $param string
1347 function passThrough( $param ) {
1352 * Create a new fatal error
1354 * @return FileRepoStatus
1356 function newFatal( $message /*, parameters...*/ ) {
1357 $params = func_get_args();
1358 array_unshift( $params, $this );
1359 return MWInit
::callStaticMethod( 'FileRepoStatus', 'newFatal', $params );
1363 * Create a new good result
1365 * @return FileRepoStatus
1367 function newGood( $value = null ) {
1368 return FileRepoStatus
::newGood( $this, $value );
1372 * Delete files in the deleted directory if they are not referenced in the filearchive table
1376 public function cleanupDeletedBatch( $storageKeys ) {}
1379 * Checks if there is a redirect named as $title. If there is, return the
1380 * title object. If not, return false.
1383 * @param $title Title of image
1386 public function checkRedirect( Title
$title ) {
1391 * Invalidates image redirect cache related to that image
1392 * Doesn't do anything for repositories that don't support image redirects.
1395 * @param $title Title of image
1397 public function invalidateImageRedirect( Title
$title ) {}
1400 * Get the human-readable name of the repo
1404 public function getDisplayName() {
1405 // We don't name our own repo, return nothing
1406 if ( $this->isLocal() ) {
1409 // 'shared-repo-name-wikimediacommons' is used when $wgUseInstantCommons = true
1410 return wfMessageFallback( 'shared-repo-name-' . $this->name
, 'shared-repo' )->text();
1414 * Returns true if this the local file repository.
1418 public function isLocal() {
1419 return $this->getName() == 'local';
1423 * Get a key on the primary cache for this repository.
1424 * Returns false if the repository's cache is not accessible at this site.
1425 * The parameters are the parts of the key, as for wfMemcKey().
1429 function getSharedCacheKey( /*...*/ ) {
1434 * Get a key for this repo in the local cache domain. These cache keys are
1435 * not shared with remote instances of the repo.
1436 * The parameters are the parts of the key, as for wfMemcKey().
1440 function getLocalCacheKey( /*...*/ ) {
1441 $args = func_get_args();
1442 array_unshift( $args, 'filerepo', $this->getName() );
1443 return call_user_func_array( 'wfMemcKey', $args );
1447 * Get an UploadStash associated with this repo.
1449 * @return UploadStash
1451 public function getUploadStash() {
1452 return new UploadStash( $this );